package com.yc.mybatis.plus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.po.LikeTable;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;

public class MyBatisPlusConfig {
    static SqlSessionFactory sqlSessionFactory;

    public static void configMyBatisPlus() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        // 开启返回主键值功能
        configuration.setUseGeneratedKeys(true);
        // 创建 MyBatisPlus 插件对象
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 构建 MyBatisPlus 分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        // 添加 MyBatisPlus 拦截器插件
        configuration.addInterceptor(interceptor);
        // 扫描 mapper 接口所在包
        configuration.addMappers("com.yc.mybatis.plus.dao");
        // 配置日志实现
        configuration.setLogImpl(Log4jImpl.class);
        // 构建 mybatis-plus 需要的 globalconfig
        GlobalConfig globalConfig = new GlobalConfig();
        // 此参数会自动生成实现 BaseMapper 的基础方法映射
        globalConfig.setSqlInjector(new DefaultSqlInjector());
        // 设置id生成器
        globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator());
        // 设置超类 mapper
        globalConfig.setSuperMapperClass(BaseMapper.class);
        // 给 configuration 注入 GlobalConfig 里面的配置
        GlobalConfigUtils.setGlobalConfig(configuration, globalConfig);
        // 设置数据源
        Environment environment = new Environment("数据库环境名",
                new JdbcTransactionFactory(),
                new PooledDataSource("com.mysql.jdbc.Driver",
                        "jdbc:mysql://127.0.0.1:3306/vaccine",
                        "root",
                        "aaaaaaaa"));
        configuration.setEnvironment(environment);
        // 构建 sqlSessionFactory
          sqlSessionFactory = builder.build(configuration);
//        this.session = sqlSessionFactory.openSession();
    }
    public static  SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
    public static void generate(){
// 使用 FastAutoGenerator 快速配置代码生成器
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/txx", "root", "aaaaaaaa")
                .globalConfig(builder -> {
                    builder.author("k") // 设置作者
                            .outputDir("src/main/java"); // 输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.yc.txx") // 设置父包名
                            .entity("entity") // 设置实体类包名
                            .mapper("dao") // 设置 Mapper 接口包名
                            .service("service") // 设置 Service 接口包名
                            .serviceImpl("service.impl") // 设置 Service 实现类包名
                            .xml("mappers"); // 设置 Mapper XML 文件包名
                })
                .strategyConfig(builder -> {
                    //只生成以tbl_开头的表的实体，且会过滤掉tbl_->得到的就是去掉前缀的名字
                    builder.addFieldPrefix("")
//                    builder.likeTable(new LikeTable("%"))
//                    builder.addInclude("table1", "table2") // 设置需要生成的表名
                            .entityBuilder()
                            .enableLombok() // 启用 Lombok
                            .enableTableFieldAnnotation() // 启用字段注解
                            .controllerBuilder()
                            .enableRestStyle(); // 启用 REST 风格
                })
//                .templateEngine(new FreemarkerTemplateEngine()) // 使用 Freemarker 模板引擎
                .execute(); // 执行生成
    }

    public static void main(String[] args) {
        generate();
    }
    static {
        try {
            configMyBatisPlus();
        } catch (IOException e) {
            throw new RuntimeException("MyBatisPlus 配置失败",e);
        }
    }
}
